#define _CRT_SECURE_NO_WARNINGS 1
#include"List.h"

struct ListNode* ListNodeInit()
{
	struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
	assert(node);
	node->next = node;
	node->prev = node;
	return node;
}

struct ListNode* BuyListNode(LTDataType x)
{
	struct ListNode* newnode = (struct ListNode*)malloc(sizeof(struct ListNode));
	assert(newnode);
	newnode->data = x;
	newnode->next = NULL;
	newnode->prev = NULL;
	return newnode;
}

void ListPrint(struct ListNode* phead)
{
	assert(phead);
	struct ListNode* cur = phead->next;
	while (cur!=phead)
	{
		printf("%d ",cur->data);
		cur = cur->next;
	}
}

void ListNodePushBack(struct ListNode* phead, LTDataType x)
{
	assert(phead);
	//struct ListNode* newnode = BuyListNode(x);
	//struct ListNode* tail = phead->prev;
	//newnode->data = x;
	//newnode->next = phead;
	//newnode->prev = tail;
	//tail->next = newnode;
	//phead->prev = newnode;
	ListNodeInsert(phead,x);
}

void ListNodePopBack(struct ListNode* phead)
{
	assert(phead);
	assert(phead->next!=phead);
	//struct ListNode* tail = phead->prev;
	//tail->prev->next = phead;
	//phead->prev = tail->prev;
	//free(tail);
	ListNodeErase(phead->prev);
}


void ListNodePushFront(struct ListNode* phead, LTDataType x)
{
	assert(phead);
	//struct ListNode* newnode = BuyListNode(x);
	//struct ListNode* next = phead->next;
	//newnode->next = next;
	//next->prev = newnode;
	//phead->next = newnode;
	//newnode->prev = phead;
	ListNodeInsert(phead->next,x);
}


void ListNodePopFront(struct ListNode* phead)
{
	assert(phead);
	assert(phead->next!=phead);
	//struct ListNode* next = phead->next;
	//struct ListNode* Next = next->next;
	//phead->next = Next;
	//Next->prev = phead;
	//free(next);
	ListNodeErase(phead->next);
}

void ListNodeInsert(struct ListNode* pos, LTDataType x)
{
	assert(pos);
	struct ListNode* posPrev = pos->prev;
	struct ListNode* newnode = BuyListNode(x);
	//posPrev newnode pos
	posPrev->next = newnode;
	newnode->prev = posPrev;
	newnode->next = pos;
	pos->prev = newnode;
}

struct ListNode* ListNodeFind(struct ListNode* phead, LTDataType x)
{
	assert(phead);
	struct ListNode* cur = phead->next;
	while (cur->next != phead)
	{
		if (cur->data == x)
			return cur;
		cur = cur->next;
	}
	return NULL;
}

void ListNodeErase(struct ListNode* pos)
{
	assert(pos);
	struct ListNode* posPrev=pos->prev;
	struct ListNode* posNext = pos->next;
	posPrev->next = posNext;
	posNext->prev = posPrev;
	free(pos);
}


void ListNodeDestroy(struct ListNode* phead)
{
	assert(phead);
	assert(phead->next != phead);
	struct ListNode* cur = phead->next;
	while (cur != phead)
	{
		struct LIstNode*next = cur->next;
		free(cur);
		cur = next;
	}
	free(phead);
}